﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using TByte.XnaHelper.GameObjects;
using Microsoft.Xna.Framework;

namespace TByte.XnaHelper.GameObjects
{
	public class AnimationGameObject : GameObject
	{
        #region Fields
        SpriteSheet sheet;
        float frame;
        float fps;
        bool playing;
        bool visible;
        bool loop;
        int begin;
        int end;
        int count;
        public event AnimationFinishedEventHandler AnimationFinished;
        bool mirror;
        #endregion

        #region Methods
        public override void Update()
        {
            if (playing)
                frame += Manager.GameTime.ElapsedGameTime.Milliseconds * fps / 1000f;
            
            if (frame > end)
            {
                if (loop)
                    frame = Math.Abs((frame - begin) % count) + begin;
                else if (AnimationFinished != null)
                {
                    AnimationFinished(this);
                    playing = false;
                }
            }
            base.Update();
        }
        public override void Draw(SpriteBatch spriteBatch)
        {
            if(visible)
                sheet.Draw(spriteBatch, Position, (int)frame,Color.White,0,1,mirror ? SpriteEffects.FlipHorizontally : SpriteEffects.None);
            base.Draw(spriteBatch);
        }
        public void Reset()
        {
            frame = begin;
        }
        #endregion

        #region Constructors
        public AnimationGameObject(SpriteSheet sheet,float fps, string name)
            : base(name)
        {
            this.sheet = sheet;
            this.frame = 0;
            this.fps = fps;
            this.end = sheet.Count - 1;
            this.begin = 0;
            this.count = end - begin;
        }
        public AnimationGameObject(SpriteSheet sheet, float fps,int begin, int end, string name)
            : base(name)
        {
            this.sheet = sheet;
            this.frame = begin;
            this.fps = fps;
            this.end = end % sheet.Count; //Prevent from incorrect entries
            this.begin = begin % sheet.Count; //Prevent incorrect entries
            this.count = end - begin;
        }
        #endregion

        #region Properties
        public bool Playing { get { return playing; } set { playing = value; } }
        public bool Visible { get { return visible; } set { visible = value; } }
        public bool Looping { get { return loop; } set { loop = value; } }
        public bool Mirror { get { return mirror; } set { mirror = value; } }
        #endregion

        public delegate void AnimationFinishedEventHandler(AnimationGameObject sender);
	}
}
